grep command
grep
- print lines that match patterns
grep
searches for PATTERNS
in each FILE
or input. PATTERNS
is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS
should be quoted when grep is used in a shell command. It’s great for finding specific lines in logs, code, or any text data.
Usage: grep [OPTION]... PATTERNS [FILE]...
OPTION
: Flags which enhances thegrep
abilities.FILE
: A FILE or standard input to search. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input.PATTERNS
: The text or regular expression to search for. PATTERNS is one or more patterns separated by newline characters.
Examples
-
Basic Search in a File
Search for a string in a file and display matching lines.
$ grep "error" logfile.txt
- Prints all lines in
logfile.txt
containing "error". - Case-sensitive by default.
- Prints all lines in
-
Case-Insensitive Search
Use
-i
to ignore case differences.$ grep -i "Error" logfile.txt
- Matches "error", "ERROR", "Error", etc.
-
Searching Multiple Files
Pass multiple files to search them all.
$ grep "warning" file1.txt file2.txt
- Shows matches from both files, prefixed with filenames (e.g.,
file1.txt:warning here
).
- Shows matches from both files, prefixed with filenames (e.g.,
-
Recursive Search
Use
-r
to search all files in a directory recursively.grep -r "TODO" /home/user/code/
- Finds "TODO" in all files under
/home/user/code/
.
- Finds "TODO" in all files under
-
Line Numbers
Add
-n
to show line numbers with matches.$ grep -n "error" logfile.txt
- Output:
5: disk error occurred
(line 5 contains "error").
- Output:
-
Matching Whole Words
Use
-w
to match only complete words.$ grep -w "run" script.sh
- Matches "run" but not "running" or "runner".
-
Inverted Search
Use
-v
to show lines that don’t match the pattern.$ grep -v "success" logfile.txt
- Displays all lines without "success".
-
Counting Matches
Use
-c
to count matching lines per file.grep -c "error" logfile.txt
- Output:
3
(if "error" appears on 3 lines).
- Output:
-
Piping Input
Search output from another command.
ps aux | grep "firefox"
- Finds processes containing "firefox" in their details.
-
Basic Regular Expressions
grep
supports regex for advanced patterns:.
: Any single character*
: Zero or more occurrences^
: Start of line$
: End of line
grep "^ERROR" logfile.txt
- Matches lines starting with "ERROR".
Example with Wildcard:
grep "err.*" logfile.txt
- Matches "error", "erratic", etc.
To get help related to the grep
command use --help
option
$ grep --help